/**
 * Created by qijialin on 2016/12/2.
 * 用户组管理功能实现的js
 */
//*******************************               用户组               *******************************/


var addDivIndex = 0;    //添加层的索引
var editDivIndex = 0;   //修改层的索引
//var signDivIndex = 0;   //签名层的索引
var groupUsersEditDivIndex = 0; //组成员调整层的索引
var groupAuthorityEditDivIndex = 0; //组成员调整层的索引

var operate = 0;
var ugid = 0;
var code = '1';
var name = '1';
var desc = '1';
var sid = 100;
var isSign = false;

var userGroupFindUrl = serverPath + 'userGroups/find';
var userGroupAddUrl = serverPath + 'userGroups/add';
var userGroupEditUrl = serverPath + 'userGroups/update';
var userGroupInvalidUrl = serverPath + 'userGroups/invalid';
var userGroupLockUrl = serverPath + 'userGroups/lock';
var userGroupUserGetUrl = serverPath + 'userGroups/get/users';
var userGetUrl = serverPath + 'users/get/user';
var guoupAuthorityGetUrl = serverPath +"authorities/query/UgAuth";
var guoupNoAuthorityGetUrl = serverPath +"authorities/query/exit";
var guoupAuthorityAddUrl = serverPath +"authorities/addAuth";
var guoupAuthorityRemoveUrl = serverPath +"authorities/deleteAuth";

layui.use('form', function(){
    var form = layui.form();
    var canDo = false;
    //自定义验证规则
    var canDo = form.verify({
        debug : true,
        ugCode: function(value) {
            if(value.length < 5) {
                layer.tips("用户组代码至少得5个字符啊",$("#userGroupCode"),{tipsMore: true,zIndex: layer.zIndex});
                return false;
                //return "1";
                //return '用户组代码至少得5个字符啊';
            }
        },
        ugName: function(value) {
            if(value.length <= 0) {
                layer.tips("用户组名不能为空",$("#userGroupName"),{tipsMore: true,zIndex: layer.zIndex});
                return false;
                //return "2";
                //return '组名代码至少得5个字符啊';
            }
        },
        content: function(value) {
            return true;
            //layedit.sync(editIndex);
        }
    });

    //监听提交
    form.on('submit(test)', function(data){
        //layer.msg(JSON.stringify(data.field));
        if(canDo){
            EditSave();
        }

    });
});

//加载的时候运行
$(function () {
    //加载数据
    FindData();
    //查询
    $("#search").click(function () {
        FindData();
    });

    //新增按钮事件1
    $('#ugAdd').click(function () {
        isSign = false;
        var url = "UserGroupEdit.html";
        $("#AddUserGroupDiv").load(url, function () {
            operate = 1;
        });
        //addDivIndex = ShowLayer($("#AddUserGroupDiv"));
        addDivIndex = ShowLayer($("#AddUserGroupDiv"), '新增用户组',  '950px', '500px');

    });

    //修改按钮事件2
    $('#ugEdit').click(function () {
        isSign = false;
        //收集参数
        var url = 'UserGroupEdit.html';
        var data = getSelectedRow();
        ugid = data.id;
        code = data.code;
        name = data.name;
        desc = data.description;
        $("#EditUserGroupDiv").load(url, function () {
            $('#userGroupCode').val(code);
            $('#userGroupName').val(name);
            $('#description').val(desc);
            operate = 2;
        });
        //editDivIndex = ShowLayer($("#EditUserGroupDiv"));
        editDivIndex = ShowLayer($("#EditUserGroupDiv"), '修改用户组', '375px', '300px');
    });

    //删除按钮事件3
    $('#ugDelete').click(function () {
        isSign = false;
        data = getSelectedRow();
        ugid = data.id;
        operate = 3;
        CallSign(100, SignCallBack);
    });

    //编辑用户组成员4
    $('#groupUsersEdit').click(function () {
        isSign = false;
        operate = 4;
        var url = 'UserGroupMember.html';
        var data = null;
        data = getSelectedRow();
        ugid = data.id;
        $("#EditGroupUsersDiv").val(null);
        $("#EditGroupUsersDiv").load(url, function () {
            $('#tableLeft').bootstrapTable();       //初始化表格
            $('#tableLeft').bootstrapTable('resetView');
            //$('#tableLeft').css({'margin-top':'-1px'});
            //$('#tableLeft').attr('data-height','300px');
            //$('#tableLeft').parent().attr('data-height','300px')
            $('#tableRight').bootstrapTable();
            $('#tableRight').bootstrapTable('resetView');
            //$('#tableRight').css({'margin-top':'-1px'});
            //$('#tableRight').attr('data-height','300px');
            //$('#tableRight').parent().attr('data-height','300px')


            operate = 4;
            $('#userGroupNameMember').val(data.name);
            $('#userGroupDes').val(data.description);
            LoadGroupUsersEdit(ugid);
        });
        groupUsersEditDivIndex = ShowLayer($("#EditGroupUsersDiv"), '组成员管理', '950px', '500px');

    });

    //用户组权限6
    $('#groupAuthorityEdit').click(function () {
        isSign = false;
        operate = 6;
        var url = 'UserGroupAuthority.html';
        var data = null;
        data = getSelectedRow();
        ugid = data.id;
        $("#EditGroupAuthorityDiv").val(null);
        $("#EditGroupAuthorityDiv").load(url, function () {
            operate = 6;
            $('#userGroupNameAuthority').val(data.name);
            $('#userGroupDesAuthority').val(data.description);
            LoadGroupAuthorityEdit(ugid);
        });
        groupAuthorityEditDivIndex = ShowLayer($("#EditGroupAuthorityDiv"), '组权限控制', '950px', '500px');
    });

    //锁定用户组5
    $('#groupLock').click(function () {
        isSign = false;
        operate = 5;
        CallSign(100, SignCallBack);
    });

    $(window).resize(function(){
        $('#tableLeft').bootstrapTable('resetView');
        $('#tableRight').bootstrapTable('resetView');
        $('#AuthorityLeft').bootstrapTable('resetView');
        $('#AuthorityRight').bootstrapTable('resetView');
    });

    //单击行触发的事件
    $('#userGroupTable').on('click-row.bs.table', function (e, row, element){
        //拿到行选中的数据
        var selectedStatusDesc = row["statusDescription"];

        //设置按钮状态
        if (selectedStatusDesc == "失效")
        {
            $('#ugEdit').attr("disabled", true);
            $('#groupUsersEdit').attr("disabled", true);
            $('#groupAuthorityEdit').attr("disabled", true);
            $('#ugDelete').attr("disabled", true);
        }else {
            $('#ugEdit').attr("disabled", false);
            $('#groupUsersEdit').attr("disabled", false);
            $('#groupAuthorityEdit').attr("disabled", false);
            $('#ugDelete').attr("disabled", false);
        }
    });

});

//查找数据
function FindData() {
    var code = $("#code").val().trim();
    var name = $("#name").val().trim();
    var valid = $("#valid option:selected").val();

    $.ajax({
        url: userGroupFindUrl,
        data: {"code": code, "name": name, "valid": valid},
        xhrFields:{ withCredentials:true},
        dataType: "json",
        //async: false,
        success: function (result) {
            var data = result.data;
            $("#userGroupTable").bootstrapTable('load', data);
        },
        error: function () {
            //alert(1111);
        }

    });

    $('#ugEdit').attr("disabled", true);
    $('#groupUsersEdit').attr("disabled", true);
    $('#groupAuthorityEdit').attr("disabled", true);
    $('#ugDelete').attr("disabled", true);
}

//弹出Div层
function ShowLayer(showDiv) {
    var divIndex = layer.open({
        //layer提供了5种层类型。可传入的值有：0（信息框，默认）；1（页面层）；2（iframe层）；3（加载层）；4（tips层）。
        // 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
        type: 1,
        //动画
        anim: 5,
        //title ：String
        //title: ['文本', 'font-size:18px;']
        //title: false 不显示标题栏
        title: ['', 'font-size:18px;font-weight:bold;'],
        //是否固定弹出
        fix: false,
        //最大小化按钮
        maxmin: false,
        //控制点击弹层外区域关闭
        shadeClose: false,
        //窗口大小 area: ['400px', '500px'] or auto 自适应大小
        area: ['350px', '370px'],
        //area: '350px',
        //iframe层的url
        //content: 'http://www.baidu.com',
        content: showDiv,
        //是否允许拉伸
        resize: false,
        //浏览器滚动条
        scrollbar: false,
        zIndex: layer.zIndex, //重点1
        end: function () {
            //alert("close");
        }
    });
    //alert('return');
    return divIndex;
}

/**弹出Div层
 * @param showDiv   需要弹出的div元素
 * @param title     弹出层的标题
 * @param width     弹出层宽度
 * @param height    弹出层高度
 * @returns {*}     返回弹出层索引
 * @constructor
 */
function ShowLayer(showDiv, title,width,height) {
    var divIndex = layer.open({
        //layer提供了5种层类型。可传入的值有：0（信息框，默认）；1（页面层）；2（iframe层）；3（加载层）；4（tips层）。
        // 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
        type: 1,
        //动画
        anim: 5,
        //title ：String
        //title: ['文本', 'font-size:18px;']
        //title: false 不显示标题栏
        title: [title, 'font-size:18px;font-weight:bold;'],
        //是否固定弹出
        fix: false,
        //最大小化按钮
        maxmin: false,
        //控制点击弹层外区域关闭
        shadeClose: false,
        //窗口大小 area: ['400px', '500px'] or auto 自适应大小
        area: [width, height],
        //area: '350px',
        //iframe层的url
        //content: 'http://www.baidu.com',
        content: showDiv,
        //是否允许拉伸
        resize: false,
        //浏览器滚动条
        //scrollbar: false,
        zIndex: layer.zIndex, //重点1
        end: function () {
            //alert("close");
        }
    });
    //alert('return');
    return divIndex;
};

//获取表格的选中行
function getSelectedRow() {
    var selects = $('#userGroupTable').bootstrapTable('getSelections');
    return selects[0];//返回选中行所有数据
}

//**********************************            新增 or 修改          *************************************/

//获取当前输入
function GetUserGroupNow() {
    code = $('#userGroupCode').val();
    name = $('#userGroupName').val();
    desc = $('#description').val();
}

//新增用户组方法
function AddUserGroup(sdid) {
    var url = userGroupAddUrl;
    var data = {"code": code, "name": name, "description": desc, "sdid": sdid};
    var type="post";
    UpdateUserGroup(url, data, type);
}

//调整用户组成员方法
function EditUserGroup(sdid) {
    var url = userGroupEditUrl;
    var data = {"id": ugid, "code": code, "name": name, "description": desc, "sdid": sdid};
    var type="put";
    UpdateUserGroup(url, data, type);
}

//用户组失效
function InvalidUserGroup(sdid) {
    var rowdata = getSelectedRow();
    ugid = rowdata.id;
    var url = userGroupInvalidUrl;
    var data = {"id": ugid, "sdid": sdid};
    var type="put";
    UpdateUserGroup(url, data, type);
}

//用户组锁定
function LockUserGroup(sdid){
    var rowdata = getSelectedRow();
    ugid = rowdata.id;
    var url = userGroupLockUrl;
    var data = {"id": ugid, "sdid": sdid};
    var tpye="put";
    UpdateUserGroup(url, data,type);
}

/**签名确认后的回调处理 真实的数据操作
 * @param sdid  签名返回的ID
 * @constructor
 */
 function SignCallBack(sdid) {
    if (operate == 1) {
        AddUserGroup(sdid);
    }
    if (operate == 2) {
        EditUserGroup(sdid);
    }
    if (operate == 3) {
        InvalidUserGroup(sdid);
    }
    if (operate == 4) {
        GroupUserEditSave(sdid);
    }
    if (operate == 5) {
        LockUserGroup(sdid);
    }
    if (operate == 6) {
        GroupAuthorityEditSave(sdid);
    }
}

/**修改数据
 * @param url   执行方法的url
 * @param data  json数据
 * @constructor
 */
function UpdateUserGroup(url, data, type) {

    $.ajax({
        url: url,
        type: type,
        data: data,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        async: false,
        success: function (result) {
            var errCode = result.errorCode
            if (errCode == 0) {
                ShowMsg('成功');
                AfterEdit();
            }
            else {
                AfterEdit();
                layer.alert('失败：错误代码[' + errCode + ']');
            }
        },
        error: ShowMsg('失败')
    })
}

//function UpdateUserGroup(url, data) {
//    $.ajax({
//        url: url,
//        type: 'put',
//        data: data,
//        dataType: "json",
//        async: false,
//        success: function (result) {
//            var errCode = result.errorCode
//            if (errCode == 0) {
//                ShowMsg('成功');
//                AfterEdit();
//            }
//            else {
//                AfterEdit();
//                layer.alert('失败：错误代码[' + errCode + ']');
//            }
//        },
//        error: ShowMsg('失败')
//    });
//}

//提示信息  可以转移到父页面中弹出
function ShowMsg(msg) {
    var msgInfo = '';
    if (operate == 1) {
        msgInfo = '新增' + msg + '！';
    }
    else if (operate == 2) {
        msgInfo = '修改' + msg + '！';
    }
    else if (operate == 3) {
        msgInfo = '失效操作' + msg + '！';
    }
    else if (operate == 4) {
        msgInfo = '用户组成员调整' + msg + '！';
    }
    else if (operate == 5) {
        msgInfo = '锁定用户组' + msg + '！';
    }
    else if (operate == 6) {
        msgInfo = '用户组授权' + msg + '！';
    }
    var index = layer.msg(msgInfo, {
            icon: 1,
            time: 1000, //1秒关闭（如果不配置，默认是3秒）
            zIndex: layer.zIndex //重点1
        },
        function () {
            //if (msg == '成功') layer.close(index);
        });
}

//保存
function EditSave() {
    GetUserGroupNow();
    //保存处理
    CallSign(100, SignCallBack);
}

//取消
function EditCancel() {
    if (operate == 1) {
        layer.close(addDivIndex);
    }
    else {
        layer.close(editDivIndex);
    }
}

//根据名称获取Url中某个参数的值
function GetUrlParam(pname) {
    var reg = new RegExp("(^|&)" + pname + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

//执行数据操作后执行的方法 如：关闭层、刷新
function AfterEdit() {
    layer.close(signDivIndex);
    if (operate == 1) {
        layer.close(addDivIndex);
    }
    else {
        layer.close(editDivIndex);
    }
    FindData();
}

//字符串方法 format
String.prototype.format = function () {
    if (arguments.length == 0) return this;
    for (var s = this, i = 0; i < arguments.length; i++)
        s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
    return s;
}

//**********************************              用户组成员               *************************************/
//定义数组，分别存储添加和删除的用户id
var leftIdArr = new Array();    //add
var rightIdArr = new Array();   //remove

/**
 * 用户组层数据加载
 * @param ugId
 * @constructor
 */
function LoadGroupUsersEdit(ugIdNow){
    LoadUsers(userGetUrl,$('#tableLeft'),ugIdNow);
    LoadUsers(userGroupUserGetUrl,$('#tableRight'),ugIdNow);
    leftIdArr = [];
    rightIdArr = [];
}

//根据组获取用户数据
function LoadUsers(url ,table,ugIdNow) {
    $.ajax({
        url: url,
        data: {"id": ugIdNow},
        dataType: "json",
        xhrFields:{ withCredentials:true},
        //async: false,
        success: function (result) {
            var data = result.data;
            table.bootstrapTable('load', data);
        },
        error: function () {
        }
    });
}

//把用户移进用户组
function MoveInGroupUser(){
    //获得选中的数据，并插入到右边表格中
    var selectLeft = $('#tableLeft').bootstrapTable('getSelections');
    $('#tableRight').bootstrapTable("prepend", selectLeft);

    //删除左边表选中的数据
    var selects = $('#tableLeft').bootstrapTable('getSelections');
    var leftid = $.map(selects, function (row) {
        return row.id;
    });
    $('#tableLeft').bootstrapTable('remove', {
        field: 'id',
        values: leftid
    });

    /**********************************************/
    //遍历选中的数据，判断id是否存在rightIdArr中
    //如果是，则从rightIdArr中删除
    //如果不是则添加到leftIdArr中
    $.each(selectLeft, function (index, obj) {
        var lid = obj.id;
        if (rightIdArr.length == 0)
        {
            leftIdArr.push(lid);
        }
        else {

            for (var i=0; i<rightIdArr.length; i++)
            {
                if (lid == rightIdArr[i])
                {
                    rightIdArr.splice(i,1);
                    return;
                }
            }
            leftIdArr.push(lid);
        }
    });
}

//把用户从用户组移除
function MoveOutGroupUser(){
    //获得选中的数据，并插入到左边表格中
    var selectRight = $('#tableRight').bootstrapTable('getSelections');
    $('#tableLeft').bootstrapTable("prepend", selectRight);

    //删除左边表选中的数据
    var selects = $('#tableRight').bootstrapTable('getSelections');
    var rightid = $.map(selects, function (row) {
        return row.id;
    });
    $('#tableRight').bootstrapTable('remove', {
        field: 'id',
        values: rightid
    });

    /**********************************************/
    //遍历选中的数据，判断id是否存在leftIdArr中
    //如果是，则从leftIdArr中删除
    //如果不是则添加到rightIdArr中
    $.each(selectRight, function (index, obj) {
        var rid = obj.id;
        if (leftIdArr.length == 0)
        {
            rightIdArr.push(rid);
        }
        else {
            for (var i=0; i<leftIdArr.length; i++)
            {
                if (rid == leftIdArr[i])
                {
                    leftIdArr.splice(i,1);
                    return;
                }
            }
            rightIdArr.push(rid);
        }
    });
}

//用户组成员调整--确定按钮事件
function btnGroupUserEditSave(){
    CallSign(100, SignCallBack);
}
//用户组成员调整--取消按钮事件
function btnGroupUserEditCancel(){
    //$('#tableLeft').bootstrapTable('resetView');
    //$('#tableRight').bootstrapTable('resetView');
    layer.close(groupUsersEditDivIndex);
}

//调整用户组成员
function GroupUserEditSave(sdid) {
    if(leftIdArr.length != 0 && rightIdArr.length != 0){
        UserGroupMemberAddRemove(sdid);
    }
    else if (leftIdArr.length != 0 && rightIdArr.length == 0){
        UserGroupMemberAdd(sdid);
    }
    else if (leftIdArr.length == 0 && rightIdArr.length != 0){
        UserGroupMemberRemove(sdid);
    }
}

//调整用户组成员完成之后
function AfterGroupUserEditSuccess(){
    layer.close(signDivIndex);
    LoadGroupUsersEdit(ugid);
    ShowMsg("成功");
}

//先添加 再删除
function UserGroupMemberAddRemove(sdid){
    if (leftIdArr.length != 0) {
        var url = serverPath+"userGroups/addMember";
        var data = {"id": ugid, "uidList": leftIdArr, "sdid": sdid};

        $.ajax({
            url: url,
            data: data,
            traditional: true,
            xhrFields:{ withCredentials:true},
            type: "post",
            dataType: "json",
            success: function (result) {
                var err = result.errorCode;
                if (err == 0) {
                    leftIdArr = [];
                    UserGroupMemberRemove(sdid);
                } else {
                    alert("数据处理失败：" + err);
                    return;
                }
            },
            error: function () {
                alert("请求失败");
                return;
            },
        });
    }
}

//向用户组添加成员
function UserGroupMemberAdd(sdid){
    if (leftIdArr.length != 0) {
        var url = serverPath+"userGroups/addMember";
        var data = {"id": ugid, "uidList": leftIdArr, "sdid": sdid};

        $.ajax({
            url: url,
            data: data,
            traditional: true,
            xhrFields:{ withCredentials:true},
            type: "post",
            dataType: "json",
            success: function (result) {
                var err = result.errorCode;
                if (err == 0) {
                    AfterGroupUserEditSuccess();
                } else {
                    alert("数据处理失败：" + err);
                    return;
                }
            },
            error: function () {
                alert("请求失败");
                return;
            },
        });
    }
}

//从用户组移除成员
function UserGroupMemberRemove(sdid){
    if (rightIdArr.length != 0) {
        var url = serverPath+"userGroups/deleteMember";
        var data = {"id": ugid, "uidList": rightIdArr, "sdid": sdid};
        $.ajax({
            url: url,
            data: data,
            traditional: true,
            xhrFields:{ withCredentials:true},
            type: "delete",
            dataType: "json",
            success: function (result) {
                var err = result.errorCode;
                if (err == 0) {
                    AfterGroupUserEditSuccess();
                } else {
                    alert("数据处理失败：" + err);
                    return;
                }
            },
            error: function () {
                alert("请求失败");
            },
        });
    }
    else{

    }

}

//**********************************                  权 限                    *************************************/

//定义数组，分别存储添加和删除的权限的id
var addIdArr = new Array();    //add
var removeIdArr = new Array();   //remove

/**
 * 用户组层数据加载
 * @param ugId
 * @constructor
 */
function LoadGroupAuthorityEdit(ugIdNow){
    var leftOutGroupAuthorityUrl = guoupNoAuthorityGetUrl;
    var rightInGroupAuthorityUrl = guoupAuthorityGetUrl;
    LoadGroupAuthority(leftOutGroupAuthorityUrl,$('#AuthorityLeft'),ugIdNow);
    LoadGroupAuthority(rightInGroupAuthorityUrl,$('#AuthorityRight'),ugIdNow);
    addIdArr = [];
    removeIdArr = [];
}

//根据组获取用户数据
function LoadGroupAuthority(url ,table,ugIdNow) {
    $.ajax({
        url: url,
        data: {"ugid": ugIdNow},
        dataType: "json",
        xhrFields:{ withCredentials:true},
        //async: false,
        success: function (result) {
            var data = result.data;
            table.bootstrapTable('load', data);
        },
        error: function () {
        }
    });
}

//把权限赋与用户组
function MoveInGroupAuthority(){
    //获得选中的数据，并插入到右边表格中
    var selectLeft = $('#AuthorityLeft').bootstrapTable('getSelections');
    $('#AuthorityRight').bootstrapTable("prepend", selectLeft);

    //删除左边表选中的数据
    var selects = $('#AuthorityLeft').bootstrapTable('getSelections');
    var leftid = $.map(selects, function (row) {
        return row.id;
    });

    $('#AuthorityLeft').bootstrapTable('remove', {
        field: 'id',
        values: leftid
    });

    /**********************************************/
    //遍历选中的数据，判断id是否存在 removeIdArr 中
    //如果是，则从 removeIdArr 中删除
    //如果不是则添加到addIdArr中
    $.each(selectLeft, function (index, obj) {
        var lid = obj.id;
        if (removeIdArr.length == 0)
        {
            addIdArr.push(lid);
        }
        else {

            for (var i=0; i<removeIdArr.length; i++)
            {
                if (lid == removeIdArr[i])
                {
                    removeIdArr.splice(i,1);
                    return;
                }
            }
            addIdArr.push(lid);
        }
    });
}

//把权限从用户组移除
function MoveOutGroupAuthority(){
    //获得选中的数据，并插入到左边表格中
    var selectRight = $('#AuthorityRight').bootstrapTable('getSelections');
    $('#AuthorityLeft').bootstrapTable("prepend", selectRight);

    //删除左边表选中的数据
    var selects = $('#AuthorityRight').bootstrapTable('getSelections');
    var rightid = $.map(selects, function (row) {
        return row.id;
    });
    $('#AuthorityRight').bootstrapTable('remove', {
        field: 'id',
        values: rightid
    });

    /**********************************************/
    //遍历选中的数据，判断id是否存在 addIdArr 中
    //如果是，则从 addIdArr 中删除
    //如果不是则添加到 removeIdArr 中
    $.each(selectRight, function (index, obj) {
        var rid = obj.id;
        if (addIdArr.length == 0)
        {
            removeIdArr.push(rid);
        }
        else {
            for (var i=0; i<addIdArr.length; i++)
            {
                if (rid == addIdArr[i])
                {
                    addIdArr.splice(i,1);
                    return;
                }
            }
            removeIdArr.push(rid);
        }
    });
}

//用户组权限调整--确定按钮事件
function btnGroupAuthorityEditSave(){
    CallSign(100, SignCallBack);
}
//用户组权限调整--取消按钮事件
function btnGroupAuthorityEditCancel(){
    //$('#tableLeft').bootstrapTable('resetView');
    //$('#tableRight').bootstrapTable('resetView');
    layer.close(groupAuthorityEditDivIndex);
}

//调整用户组权限
function GroupAuthorityEditSave(sdid) {
    if(addIdArr.length != 0 && removeIdArr.length != 0){
        UserGroupAuthorityAddRemove(sdid);
    }
    else if (addIdArr.length != 0 && removeIdArr.length == 0){
        UserGroupAuthorityAdd(sdid);
    }
    else if (addIdArr.length == 0 && removeIdArr.length != 0){
        UserGroupAuthorityRemove(sdid);
    }
}

//调整用户组权限完成之后
function AfterGroupAuthorityEditSuccess(){
    layer.close(signDivIndex);
    LoadGroupAuthorityEdit(ugid);
    ShowMsg("成功");
}

//先添加 再删除
function UserGroupAuthorityAddRemove(sdid){
    if (addIdArr.length != 0) {
        var url = guoupAuthorityAddUrl;
        var data = {"ugid": ugid, "auidList": addIdArr, "sdid": sdid};

        $.ajax({
            url: url,
            data: data,
            traditional: true,
            xhrFields:{ withCredentials:true},
            type: "post",
            dataType: "json",
            success: function (result) {
                var err = result.errorCode;
                if (err == 0) {
                    addIdArr = [];
                    UserGroupAuthorityRemove(sdid);
                } else {
                    alert("数据处理失败：" + err);
                    return;
                }
            },
            error: function () {
                alert("请求失败");
                return;
            },
        });
    }
}


//向用户组添加权限
function UserGroupAuthorityAdd(sdid){
    if (addIdArr.length != 0) {
        var url = guoupAuthorityAddUrl;
        var data = {"ugid": ugid, "auidList": addIdArr, "sdid": sdid};

        $.ajax({
            url: url,
            data: data,
            traditional: true,
            xhrFields:{ withCredentials:true},
            type: "post",
            dataType: "json",
            success: function (result) {
                var err = result.errorCode;
                if (err == 0) {
                    AfterGroupAuthorityEditSuccess();
                } else {
                    alert("数据处理失败：" + err);
                    return;
                }
            },
            error: function () {
                alert("请求失败");
                return;
            },
        });
    }
}

/**
 * 从用户组移除权限
 * @param sdid
 * @constructor
 */
function UserGroupAuthorityRemove(sdid){
    if (removeIdArr.length != 0) {
        var url = guoupAuthorityRemoveUrl;
        var data = {"ugid": ugid, "auidList": removeIdArr, "sdid": sdid};
        $.ajax({
            url: url,
            data: data,
            traditional: true,
            xhrFields:{ withCredentials:true},
            type: "delete",
            dataType: "json",
            success: function (result) {
                var err = result.errorCode;
                if (err == 0) {
                    AfterGroupAuthorityEditSuccess();
                } else {
                    alert("数据处理失败：" + err);
                    return;
                }
            },
            error: function () {
                alert("请求失败");
            },
        });
    }
    else{

    }

}

/**
 * 可弹出多个tips的方法
 * @param msg   提示信息
 * @param element   依赖的html元素
 * @constructor
 */
function ShowTips(msg,element){
    layer.tips(msg,element,{tipsMore: true,zIndex: layer.zIndex});
}

//自定义验证
function verifyUserGroupAddorEdit(){
    var vResult = false;
    var code = $("#userGroupCode").val();
    var name = $("#userGroupName").val();

    if(code.length < 5) {
        ShowTips("用户组代码至少得5个字符啊", $("#userGroupCode"));
        return vResult;
    }


    if(name.length <= 0) {
        ShowTips("用户组名不能为空", $("#userGroupName"));
        return vResult;
    }

    return vResult;
}


